package cn.zhaoyuening.crm.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.zhaoyuening.crm.dao.BaseDao;
import cn.zhaoyuening.crm.domain.CrmCourseType;
import cn.zhaoyuening.crm.utils.page.PageQueryHibernateCallback;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T>{
	private Class entityClass = 
			(Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	
	@Override
	public void save(T t) {
		getHibernateTemplate().save(t);
	}

	@Override 	
	public void delete(T t) {
		getHibernateTemplate().delete(t);
	}

	@Override
	public T findById(Serializable id) {
        T t = (T) getHibernateTemplate().get(entityClass, id);
        return t;
	}

	@Override
	public List<T> findAll() {
		List list = getHibernateTemplate().find("from "+entityClass.getSimpleName());
		return list;
	}
	
	@Override
	public void addOrEdit(T t) {
		getHibernateTemplate().saveOrUpdate(t);
	}
	
	@Override
	public List<T> findAll(String sql,Object[] objects) {
		List<T> list = getHibernateTemplate().find("from "+entityClass.getName()+" where 1=1"+sql,objects);
		return list;
	}
	
	@Override
	public long getTotalRecord() {
		String hql = "select count(c) from "+entityClass.getName()+" c";
		List list = getHibernateTemplate().find(hql);
		long totalRecord = (Long) list.get(0);
		return totalRecord;
	}
	
	@Override
	public List<T> findAll(String hql, Object[] params, int startIndex, int pageSize) {
		String mhql = "from CrmCourseType where 1=1 "+hql;
		PageQueryHibernateCallback<T> callback = new PageQueryHibernateCallback<T>();
		callback.setHql(mhql).setPageSize(pageSize).setParams(params).setStartIndex(startIndex);
		List<T> list = getHibernateTemplate().execute(callback);
		return list;
	}
}
